//
//  BaseViewController.m
//  TuanLife
//
//  Created by 伏圣文 on 2017/12/23.
//  Copyright © 2017年 HuiNaMac. All rights reserved.
//

#import "BaseViewController.h"

//#import "XCLoaderView.h"
#import "XCCustomRefresh.h"
#import "FSWCustomRefresh.h"
//#import "XCHCFHomeViewController.h"
#import "LoginController.h"
#import "MainNavigationVC.h"
@interface BaseViewController ()
 
@property (nonatomic,strong) NSArray *refreshImages;/** <刷新动画的图片数组 */ 
@property (nonatomic,assign) BOOL isHeaderRefresh;
 
@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    @weakify(self)
//    [self setNavigationLeftBarItemType:OnlyHaveImage title:@"" titleFont:0 titleColor:[UIColor whiteColor] image:[[UIImage imageNamed:@"返回（白）"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] responderBlock:^{
//        @strongify(self)
//        [self pop];
//    }];
    [self setNavigationLeftBarItemType:OnlyHaveImage title:@"" titleFont:0 titleColor:[UIColor whiteColor] image:[[UIImage imageNamed:@"back_allow_left"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] responderBlock:^{
        @strongify(self)
        [self pop];
    }];
    
//    ((StatusBarHeight == 44 || StatusBarHeight == 47 || StatusBarHeight == 50)? StatusBarHeight : 20)
    
//    self.topBackImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH*0.31)];
//    self.topBackImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NavigationBarHeight + 44)];
//    self.topBackImageView.image = [UIImage imageNamed:@"nav_top_and_view_back"];
//    self.topBackImageView.contentMode = UIViewContentModeScaleToFill;
//    [self.view addSubview:self.topBackImageView];
//    [self.view sendSubviewToBack:self.topBackImageView];
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    ///这里设置白色
    return UIStatusBarStyleLightContent;
}

-(BOOL)prefersStatusBarHidden{
    return NO;
}

- (MJRefreshHeader*)headerGifRefreshBlock:(XCRereshHeaderBlock)block
{
    self.refreshHeaderBlock = block;
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    FSWCustomRefresGifhHeader *header = [FSWCustomRefresGifhHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //    [header setState:MJRefreshStatePulling];
    
    return header;
#pragma clang diagnostic pop
}

- (MJRefreshAutoFooter*)autoFooterGifRefreshBlock:(XCRereshFooterBlock)block
{
    self.refreshFooterBlock = block;
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    return [FSWCustomRefreshGifAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
#pragma clang diagnostic pop
}

- (MJRefreshBackFooter*)backFooterGifRefreshBlock:(XCRereshFooterBlock)block
{
    self.refreshFooterBlock = block;
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    return [FSWCustomRefreshGifBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
#pragma clang diagnostic pop
}



- (MJRefreshHeader*)headerRefreshBlock:(XCRereshHeaderBlock)block
{
    self.refreshHeaderBlock = block;
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    return [XCCustomRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
#pragma clang diagnostic pop
}

- (MJRefreshAutoFooter*)autoFooterRefreshBlock:(XCRereshFooterBlock)block
{
    self.refreshFooterBlock = block;
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    return [XCCustomRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
#pragma clang diagnostic pop
}

- (MJRefreshBackFooter*)backFooterRefreshBlock:(XCRereshFooterBlock)block
{
    self.refreshFooterBlock = block;
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    return [XCCustomRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
#pragma clang diagnostic pop
}

- (void)setNavigationLeftBarItemType:(XCBarItemType)type title:(NSString *)title titleFont:(CGFloat)font titleColor:(UIColor *)color  image:(UIImage *)image responderBlock:(void (^)(void))block
{
    UIBarButtonItem* leftItem;
    switch (type) {
        case OnlyHaveImage:
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
            leftItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
#pragma clang diagnostic pop
            self.navigationItem.leftBarButtonItem = leftItem;
            break;
        case OnlyHaveTitle:
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
            leftItem = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
#pragma clang diagnostic pop
             [leftItem setTitleTextAttributes:@{NSForegroundColorAttributeName: color,NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:font]} forState:UIControlStateNormal];
            self.navigationItem.leftBarButtonItem = leftItem;
            break;
        case HaveImageAndImage:
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
            leftItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
            UIBarButtonItem* titleItem = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
#pragma clang diagnostic pop
            [titleItem setTitleTextAttributes:@{NSForegroundColorAttributeName: color,NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:font]} forState:UIControlStateNormal];
            [titleItem setTitlePositionAdjustment:UIOffsetMake(-10, 0) forBarMetrics:UIBarMetricsDefault];
            [self.navigationItem setLeftBarButtonItems:@[leftItem,titleItem]];
            break;
    }
    self.leftBarItemActionBlock = block;
}

- (void)setNavigationRightBarItemType:(XCBarItemType)type title:(NSString *)title titleFont:(CGFloat)font titleColor:(UIColor *)color image:(UIImage *)image responderBlock:(void (^)(void))block
{
    UIBarButtonItem* rightItem;
    switch (type) {
        case OnlyHaveImage:
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
            rightItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
#pragma clang diagnostic pop
            self.navigationItem.rightBarButtonItem = rightItem;
            break;
        case OnlyHaveTitle:
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
            rightItem = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
#pragma clang diagnostic pop
            [rightItem setTitleTextAttributes:@{NSForegroundColorAttributeName: color,NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:font]} forState:UIControlStateNormal];
            self.navigationItem.rightBarButtonItem = rightItem;
            break;
        case HaveImageAndImage:
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
            rightItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
            UIBarButtonItem* titleItem = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
#pragma clang diagnostic pop
            [titleItem setTitleTextAttributes:@{NSForegroundColorAttributeName: color,NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:font]} forState:UIControlStateNormal];
            [titleItem setTitlePositionAdjustment:UIOffsetMake(10, 0) forBarMetrics:UIBarMetricsDefault];
            [self.navigationItem setRightBarButtonItems:@[rightItem,titleItem]];
            break;
    }
    self.rightBarItemActionBlock = block;
}

- (UIViewController *)instantiateInitialViewControllerWithStoryboardName:(NSString *)storyboardName
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]];
    UIViewController *viewController = [storyboard instantiateInitialViewController];
    return (BaseViewController *)viewController;
}

- (UIViewController *)instantiateViewControllerWithStoryboardName:(NSString *)storyboardName identifier:(NSString *)identifier
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:identifier];
    return (BaseViewController *)viewController;
}

- (BaseViewController *)getTargetViewController:(NSString *)currentViewControllerName
{
    NSAssert(currentViewControllerName != nil, @"当前控制名称不为空");
    for (BaseViewController* viewcontrller in self.navigationController.viewControllers) {
        if ([viewcontrller isKindOfClass:NSClassFromString(currentViewControllerName)]) {
            return viewcontrller;
        }
    }
    return nil;
}

- (UIImage *)imageWithFrame:(CGRect)frame alphe:(CGFloat)alphe andColor:(UIColor*)color
{
    UIGraphicsBeginImageContext(frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[color colorWithAlphaComponent:alphe] CGColor]);
    CGContextFillRect(context, frame);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
@end

@implementation BaseViewController(Fast)
- (void)setNavigationOrigin
{
        self.navigationController.navigationBar.translucent = NO;
        UINavigationController* navigation = [[UINavigationController alloc] init];
        self.navigationController.navigationBar.shadowImage = navigation.navigationController.navigationBar.shadowImage;
    
        UIFont* font = [UIFont fontWithName:@"PingFangSC-Medium" size: 16.0];
        if (font) {
            self.navigationController.navigationBar.titleTextAttributes = @{
                                                                            NSForegroundColorAttributeName: [UIColor whiteColor],
                                                                            NSFontAttributeName:font
                                                                            };
        }else{
            self.navigationController.navigationBar.titleTextAttributes = @{
                                                                            NSForegroundColorAttributeName: [UIColor whiteColor],
                                                                            };
        }
    
    UIImage *buttonNormal = [[UIImage imageNamed:@"返回（白）"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navigationController.navigationBar setBackIndicatorImage:buttonNormal];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:buttonNormal];
    self.navigationController.navigationBar.barTintColor = XCMainColor;
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-30, 0)
                                                         forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    UIImage *image = [UIImage imageNamed:@"nav_top_and_view_back"];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
   
     [self.navigationController.navigationBar setContentMode:UIViewContentModeCenter];
    
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        //        appearance.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular];
        if (font) {
            appearance.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:font};
        }else{
            appearance.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],};
        }
        [appearance setBackgroundColor: [UIColor colorNamed:@"fDarkBuleColor"]];
        // 隐藏分割线 设置一个透明或者纯色的图片 设置nil 或者 [UIImage new]无效
        [appearance setBackgroundImage:image];
        [appearance setShadowImage:[[UIImage alloc] init]];
//        [appearance setShadowImage:[UIImage zt_imageWithPureColor:[UIColor colorNamed:@"fDarkOrgColor"]]];
        [[UINavigationBar appearance] setScrollEdgeAppearance: appearance];
    }
}

- (void)setNavigationClear
{
        self.navigationController.navigationBar.translucent = YES;
        self.navigationController.navigationBar.shadowImage = [UIImage new];
        
        [self.navigationController.navigationBar setBackgroundImage:[self imageWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NavigationBarHeight) alphe:0 andColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
        UIFont* font = [UIFont fontWithName:@"PingFangSC-Medium" size: 16.0];
        if (font) {
            self.navigationController.navigationBar.titleTextAttributes = @{
                                                                            NSForegroundColorAttributeName: [UIColor whiteColor],
                                                                            NSFontAttributeName:font
                                                                            };
        }else{
            self.navigationController.navigationBar.titleTextAttributes = @{
                                                                            NSForegroundColorAttributeName: [UIColor whiteColor],
                                                                            };
        }
    
}


- (void)setNavigationSignClear
{
        self.navigationController.navigationBar.translucent = YES;
        self.navigationController.navigationBar.shadowImage = [UIImage new];
        
        [self.navigationController.navigationBar setBackgroundImage:[self imageWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NavigationBarHeight) alphe:0 andColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
        UIFont* font = [UIFont fontWithName:@"PingFangSC-Medium" size: 16.0];
        if (font) {
            self.navigationController.navigationBar.titleTextAttributes = @{
                                                                            NSForegroundColorAttributeName: [UIColor whiteColor],
                                                                            NSFontAttributeName:font
                                                                            };
        }else{
            self.navigationController.navigationBar.titleTextAttributes = @{
                                                                            NSForegroundColorAttributeName: [UIColor whiteColor],
                                                                            };
          
        }
    UIImage *image = [UIImage new];
    //    UIImage *image = [UIImage new];
//    topBackImageView.contentMode = UIViewContentModeScaleToFill;
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
     [self.navigationController.navigationBar setContentMode:UIViewContentModeCenter];
    
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        //        appearance.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular];
        if (font) {
            appearance.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:font};
        }else{
            appearance.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],};
        }
        [appearance setBackgroundColor: [UIColor colorNamed:@"fDarkBuleColor"]];
        // 隐藏分割线 设置一个透明或者纯色的图片 设置nil 或者 [UIImage new]无效
        [appearance setBackgroundImage:image];
        [appearance setShadowImage:[[UIImage alloc] init]];
//        [appearance setShadowImage:[UIImage zt_imageWithPureColor:[UIColor colorNamed:@"fDarkOrgColor"]]];
        [[UINavigationBar appearance] setScrollEdgeAppearance: appearance];
    }
}

+ (NSArray<NSString *> *)storyboardList
{
    static NSArray *kBundleStoryboardNameList;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSMutableArray *tmp = [NSMutableArray array];
        
        /**
         *  list all storyboard files
         *  @warning ignore ~iphone ~ipad
         */
        NSArray *list = [NSBundle pathsForResourcesOfType:@"storyboardc" inDirectory:[NSBundle mainBundle].resourcePath];
        
        for(NSString *path in list) {
            NSString *ext = [path lastPathComponent];
            NSString *name = [ext stringByDeletingPathExtension];
            if([name rangeOfString:@"~"].location == NSNotFound) {
                [tmp addObject:name];
            }
        }
        kBundleStoryboardNameList = [NSArray arrayWithArray:tmp];
    });
    return kBundleStoryboardNameList;
}

+ (NSCache *)cache
{
    static NSCache *cache;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cache = [[NSCache alloc] init];
    });
    return cache;
}

+ (nullable instancetype)tryTakeOutInstanceFromStoryboardNamed:(nonnull NSString *)storyboardName identifier:(nonnull NSString *)identifier
{
    if(!storyboardName || !identifier) {
        return nil;
    }
    
    @try {
#if DEBUG
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]];
        NSString *selStr = @"identifierToNibNameMap";
        SEL sel = NSSelectorFromString(selStr);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        if([storyboard respondsToSelector:sel]) {
            id obj = [storyboard performSelector:sel];
            if(obj && [obj isKindOfClass:[NSDictionary class]] && [[(NSDictionary *)obj allValues] containsObject:identifier]) {
                id instance = [storyboard instantiateViewControllerWithIdentifier:identifier];
                return instance;
            } else {
                return nil;
            }
        } else {
            NSAssert(NO, @"unsupport Selector: identifierToNibNameMap");
        }
        
#pragma clang diagnostic pop
        
#else
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]];
        id instance = [storyboard instantiateViewControllerWithIdentifier:identifier];
        return instance;
#endif
    }@catch(NSException *exception) {
        return nil;
    } @finally {
    }
}

+ (instancetype)instanceFromStoryboardWithIdentifier:(nonnull NSString *)identifier
{
    NSAssert(identifier, @"identifier is nil!!!!");
    if(!identifier) {
        return nil;
    }
    
    NSCache *cache = [self cache];
    NSString *cacheStoryboardName = [cache objectForKey:identifier];
    if(cacheStoryboardName) {
        return [self tryTakeOutInstanceFromStoryboardNamed:cacheStoryboardName identifier:identifier];
    }
    
    for(NSString *name in [self storyboardList]) {
        id instance = [self tryTakeOutInstanceFromStoryboardNamed:name identifier:identifier];
        if(instance) {
            [cache setObject:name forKey:identifier];
            return instance;
        }
    }
    return nil;
}

+ (instancetype)fastInstantiateViewController
{
    NSString *identifier = NSStringFromClass([self class]);
    id viewController = [self instanceFromStoryboardWithIdentifier:identifier];
    if(!viewController) {
        viewController = [[[self class] alloc] init];
    }
    
    return viewController;
}

- (void)pushViewController:(UIViewController *)viewController
{
    NSAssert(self.navigationController != nil, @"navigationController is nil!");
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)pop
{
    NSAssert(self.navigationController != nil, @"navigationController is nil!");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)popToRoot
{
    NSAssert(self.navigationController != nil, @"navigationController is nil!");
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (NSArray *)popToViewController:(UIViewController *)viewController
{
    NSAssert(self.navigationController != nil, @"navigationController is nil!");
    return [self.navigationController popToViewController:viewController animated:YES];
}

@end

@implementation BaseViewController(Loader)
- (void)showPayLoader
{
    //    [XCLoadingHUD showIn:[UIApplication sharedApplication].keyWindow andText:@"汇民通" andType:PayLoading];
}

- (void)showLoader
{
    //    [XCLoadingHUD showIn:[UIApplication sharedApplication].keyWindow andText:@"" andType:circleLoading];
}

- (void)hideLoader
{
    //    [XCLoadingHUD hideIn:[UIApplication sharedApplication].keyWindow];
}

- (void)cleverLoader:(BOOL)state
{
    if(state) {
        [self showLoader];
    } else {
        [self hideLoader];
    }
}

@end

@implementation BaseViewController(MJGifRefresh)

-(void)loadMoreData
{
    self.isHeaderRefresh = NO;
    [self timeAction];
}

-(void)loadNewData
{
    self.isHeaderRefresh = YES;
    [self performSelector:@selector(timeAction) withObject:self afterDelay:1];
}

-(void)timeAction
{
    self.isHeaderRefresh ? self.refreshHeaderBlock() : self.refreshFooterBlock();
}

@end

@implementation BaseViewController (Navigation)

- (void)leftAction
{
    if (self.leftBarItemActionBlock) {
        self.leftBarItemActionBlock();
    }
}

- (void)rightAction
{
    if (self.rightBarItemActionBlock) {
        self.rightBarItemActionBlock();
    }
}

@end

@implementation BaseViewController (UMeng)

-(void)configUMengShare{
  
}
@end

@implementation BaseViewController (JPush)

-(void)configJpush:(NSString *)jpush_username {
    
//    jpush_username = @"112";
//    jpush_username = [NSString stringWithFormat:@"fshunheoa_%@",jpush_username];
    [JPUSHService setAlias:jpush_username completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        XCLog(@"极光别名设置成功");
    } seq:1];
}
@end


@implementation BaseViewController (Alert)

- (void)alertTitle:(NSString *)title andMessage:(NSString *)message andCancleBlock:(void (^ __nullable)(UIAlertAction *action))handler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:handler];
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)alertTitle:(NSString *)title andMessage:(NSString *)message andOK:(NSString*)ok andCancle:(NSString*)cancle andBlock:(void (^)(UIAlertAction *action))OK
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:ok style:UIAlertActionStyleDestructive handler:OK];
    [alertController addAction:okAction];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:cancle style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:cancleAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)alertTitle:(NSString *)title andMessage:(NSString *)message andOK:(NSString*)ok andCancle:(NSString*)cancle andBlock:(void (^)(UIAlertAction *action))OK andCancleBlock:(void (^)(UIAlertAction *action))cancleBlock
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:ok style:UIAlertActionStyleDestructive handler:OK];
    [alertController addAction:okAction];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:cancle style:UIAlertActionStyleDefault handler:cancleBlock];
    [alertController addAction:cancleAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

@end

@implementation BaseViewController (Network)
- (void)networkStatus:(void(^)(NSInteger status))block
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                XCLog(@"未知网络");
                break;
            case 0:
                XCLog(@"网络不可达");
                break;
            case 1:
                XCLog(@"GPRS网络");
                break;
            case 2:
                XCLog(@"wifi网络");
                break;
            default:
                break;
        }
        if(status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi ){
            [self hideLoader];
            block(1);
        }else{
            //            [FSWToast showWithText:@"亲，网络已断开！"];
            [self hideLoader];
            block(0);
        }
    }];
    
}

@end

@implementation BaseViewController (Login)

- (BOOL)loginAlert
{
    NSString *authToken = [fUserDefaults objectForKey:LOGIN_TOKEN];
    if (authToken.length <= 0) {
        
        LoginController *vc = [[LoginController alloc]init];
        
        MainNavigationVC *nav = [[MainNavigationVC  alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav  animated:YES completion:nil];
        
//        [self presentViewController:[[MainNavigationVC  alloc] initWithRootViewController:loginviewcontroller] animated:YES completion:nil];
        
        return YES;
    }else{
        return NO;
    }
}

@end

@implementation BaseViewController (CallCustomer)

- (void)callCustomer:(void (^ __nullable)(UIAlertAction *action))handler andOK:(void (^ __nullable)(UIAlertAction *action))okHandler
{
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",SERVICE_MOBILE]] options:@{} completionHandler:^(BOOL success) {
            handler(nil);
        }];
    }else{
        UIAlertController* alertController = [UIAlertController alertControllerWithTitle:nil message:SERVICE_MOBILE preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:handler];
        [alertController addAction:cancle];
        
        UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (okHandler) {
                okHandler(nil);
            }
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",SERVICE_MOBILE]] options:@{} completionHandler:^(BOOL success) {
                       
                 }];
        }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)callCustomer:(NSString *)phone addCall:(void (^ __nullable)(UIAlertAction *action))handler andOK:(void (^ __nullable)(UIAlertAction *action))okHandler
{
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]] options:@{} completionHandler:^(BOOL success) {
            handler(nil);
        }];
    }else{
        UIAlertController* alertController = [UIAlertController alertControllerWithTitle:nil message:phone preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:handler];
        [alertController addAction:cancle];
        
        UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (okHandler) {
                okHandler(nil);
            }
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]] options:@{} completionHandler:^(BOOL success) {
                        
            }];
        }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
@end

 
@implementation BaseViewController (versions)

- (void)getNewVersions:(void(^)(NSString *neetUpadte))block
{
    NSString *client_version = [fUserDefaults objectForKey:CLINET_VERSION];
    NSDictionary *dict = @{@"version":client_version};
    [LoginNetRequest versionUpdateRequest:dict andBlock:^(id responseObject) {
         block(responseObject);
    } andFailBlock:^(NSString *error) {
        
    }];
}


@end
  
@implementation BaseViewController (notifCode)

-(void)configUMengShare:(NSInteger)code{
    switch (code) {
        case 1001:
            
            break;
        case 1002:
            
            break;
        case 2001:
            
            break;
        case 2002:
            
            break;
        case 2003:
            
            break;
        default:
            break;
    }
}
@end
 

@implementation BaseViewController (checkVideo)

- (void) checkVideoStatus:(void(^)(NSInteger status ,NSString *message))block
{
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (authStatus) {
        case AVAuthorizationStatusNotDetermined:
            //没有询问是否开启相机
            //            self.videoStatus = @"AVAuthorizationStatusNotDetermined";
            block(0,@"没有询问是否开启相机");
            break;
        case AVAuthorizationStatusRestricted:
            //未授权，家长限制
            //            self.videoStatus = @"AVAuthorizationStatusRestricted";
            block(1,@"相机权限未打开");
            break;
        case AVAuthorizationStatusDenied:
            //未授权
            //            self.videoStatus = @"AVAuthorizationStatusDenied";
            block(2,@"相机权限未打开");
            break;
        case AVAuthorizationStatusAuthorized:
            //玩家授权
            //            self.videoStatus = @"AVAuthorizationStatusAuthorized";
            block(3,@"已授权");
            break;
        default:
            break;
    }
}
@end
